package com.valuegroup.smarttodo.ui.programme.curriculum;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.Curriculum;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.imgsel.ISNav;
import com.valuegroup.smarttodo.plugins.imgsel.config.ISListConfig;
import com.valuegroup.smarttodo.plugins.imgsel.ui.ISListActivity;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.util.AlertUtils;
import com.valuegroup.smarttodo.util.CollectionUtils;

import java.io.File;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CurriculumSetActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.btnSave)
    TextView btnSave;
    @BindView(R.id.imgCover)
    ImageView imgCover;
    @BindView(R.id.btnSetCover)
    LinearLayout btnSetCover;
    @BindView(R.id.labTitle)
    ClickableTextView labTitle;
    @BindView(R.id.labTitleEdit)
    MultilineEditText labTitleEdit;
    @BindView(R.id.labCountDay)
    TextView labCountDay;
    @BindView(R.id.labStartDt)
    TextView labStartDt;
    @BindView(R.id.btnStartDt)
    LinearLayout btnStartDt;
    @BindView(R.id.labEndDt)
    TextView labEndDt;
    @BindView(R.id.btnEndDt)
    LinearLayout btnEndDt;
    @BindView(R.id.layoutRemind)
    LinearLayout layoutRemind;
    @BindView(R.id.btnRemind)
    Switch btnRemind;
    @BindView(R.id.labRemindTime)
    TextView labRemindTime;
    @BindView(R.id.btnRemindTime)
    LinearLayout btnRemindTime;
    @BindView(R.id.btnAuto)
    Switch btnAuto;
    @BindView(R.id.labDayTarget)
    TextView labDayTarget;
    @BindView(R.id.btnDayTarget)
    LinearLayout btnDayTarget;

    private static final int REQ_CAMERA_PERMISSION = 59;
    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Curriculum DATA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_curriculum_set);
        ButterKnife.bind(this);

        initView();
        initData();
    }


    private void initData() {
        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getCurriculumService().getCurriculumDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getCurriculumService().getDefaultCurriculum();
            DATA.setTitle(null);
        }

        labTitle.setText(DATA.getTitle());
        labStartDt.setText(DateUtils.date2str(DATA.getStartDt(), DateUtils.F40));
        labEndDt.setText(DateUtils.date2str(DATA.getEndDt(), DateUtils.F40));
        btnAuto.setChecked(DATA.getOpenAuto());
        btnRemind.setChecked(DATA.getRemindTime() != null);
        if (DATA.getRemindTime() != null) {
            layoutRemind.setVisibility(View.VISIBLE);
            labRemindTime.setText(DateUtils.date2str(DATA.getRemindTime() == null ? new Date() : DATA.getRemindTime(), DateUtils.F21));
        } else {
            layoutRemind.setVisibility(View.GONE);
        }
        labDayTarget.setText(String.format(getResources().getString(R.string.curriculum_minute), DATA.getDayTargetMinute()));
        labCountDay.setText(String.format(getResources().getString(R.string.curriculum_study_count), DateUtils.dateInterval(DATA.getStartDt(), DATA.getEndDt())));

        // 设置封面图片
        if (!TextUtils.isEmpty(DATA.getImagePath())) {
            //Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
            //imgCover.setImageURI(u);
            btnSetCover.setVisibility(View.GONE);
            imgCover.setVisibility(View.VISIBLE);

            /*RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(), DATA.getImagePath());
            roundedBitmapDrawable1.setCornerRadius(6);
            imgCover.setImageDrawable(roundedBitmapDrawable1);*/

            RequestOptions options = RequestOptions
                    .bitmapTransform(new RoundedCorners(6)) //设置图片圆角角度
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true)//不做内存缓存
                    .placeholder(R.drawable.ic_default_image)//图片加载出来前，显示的图片
                    .fallback(R.drawable.ic_default_image) //url为空的时候,显示的图片
                    .error(R.drawable.ic_default_image);//图片加载失败后，显示的图片

            Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
            Glide.with(this).load(u)
                    .apply(options)
                    .into(imgCover);
        } else {
            btnSetCover.setVisibility(View.VISIBLE);
            imgCover.setVisibility(View.GONE);
        }
    }


    private void initView() {
        // 任务主干编辑状态控制
        labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(v.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });


        labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labTitleEdit.setSelection(labTitleEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labTitleEdit, 0);
                } else {
                    // 失去焦点
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(labTitleEdit.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
            }
        });

        btnRemind.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    labRemindTime.setText(DateUtils.date2str(DATA.getRemindTime() == null ? new Date() : DATA.getRemindTime(), DateUtils.F21));
                    layoutRemind.setVisibility(View.VISIBLE);
                } else {
                    DATA.setRemindTime(null);
                    layoutRemind.setVisibility(View.GONE);
                }
            }
        });

        btnAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DATA.setOpenAuto(isChecked);
            }
        });

    }

    @OnClick({R.id.btnBack, R.id.btnSave, R.id.labTitle, R.id.imgCover, R.id.btnSetCover, R.id.btnStartDt, R.id.btnEndDt, R.id.btnRemindTime, R.id.btnDayTarget, R.id.btnAuto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.labTitle:
                labTitle.setVisibility(View.GONE);

                labTitleEdit.setText(labTitle.getText());
                labTitleEdit.setVisibility(View.VISIBLE);

                // 获得焦点
                labTitleEdit.setFocusable(true);
                labTitleEdit.setFocusableInTouchMode(true);
                labTitleEdit.requestFocus();

                /*EditText不会自动获取焦点并且不会弹出键盘代码：
                将其父控件设置
                Parent.setFocusable(true);
                Parent.setFocusableInTouchMode(true);*/

                break;
            case R.id.btnBack:
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnSave:
                // 保存事件
                if (labTitle.getText().length() == 0) {
                    AlertUtils.showToast(view.getContext(), R.string.not_inset_content);
                    return;
                }
                if (DATA.getId() == null && ServiceFactory.getInstance().getCurriculumService().existCurriculumName(labTitle.getText().toString())) {
                    AlertUtils.showToast(view.getContext(), R.string.exist_content);
                    return;
                }

                DATA.setTitle(labTitle.getText().toString());
                DATA = ServiceFactory.getInstance().getCurriculumService().saveCurriculum(DATA);

                if (DATA_ID != 0) {
                    setCloseParams();
                }
                finishAfterTransition();
                break;
            case R.id.imgCover:
            case R.id.btnSetCover:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA},
                            REQ_CAMERA_PERMISSION);
                    return;
                }

                openImageSelector(true);
                break;
            case R.id.btnStartDt:
                doDatePickDialog(true, DATA.getStartDt());
                break;
            case R.id.btnEndDt:
                doDatePickDialog(false, DATA.getEndDt());
                break;
            case R.id.btnRemindTime:
                DatePickDialog dRemind = new DatePickDialog(this);
                dRemind.setType(DateType.TYPE_HM);
                dRemind.setStartDate(DATA.getRemindTime() != null ? DATA.getRemindTime() : new Date());
                dRemind.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        DATA.setRemindTime(date);
                        labRemindTime.setText(DateUtils.date2str(date, DateUtils.F21));
                    }
                });
                dRemind.show();
                break;
            case R.id.btnDayTarget:
                DatePickDialog dCount = new DatePickDialog(this);
                dCount.setType(DateType.TYPE_CUSTOM_MINUTE_INTERVAL_5);
                dCount.setStartData(DATA.getDayTargetMinute());
                dCount.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        DATA.setDayTargetMinute(DateUtils.getMinute(date));
                        labDayTarget.setText(String.format(getResources().getString(R.string.curriculum_minute), DATA.getDayTargetMinute()));
                    }
                });
                dCount.show();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }

    private void doDatePickDialog(final boolean isStart, Date initDate) {
        DatePickDialog dialog = new DatePickDialog(this);
        dialog.setType(DateType.TYPE_YMD);
        dialog.setStartDate(initDate != null ? initDate : new Date());
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                String ymd = DateUtils.date2str(date, DateUtils.F40);
                if (isStart) {
                    DATA.setStartDt(date);
                    labStartDt.setText(ymd);
                } else {
                    DATA.setEndDt(date);
                    labEndDt.setText(ymd);
                }

                labCountDay.setText(String.format(getResources().getString(R.string.curriculum_study_count), DateUtils.dateInterval(DATA.getStartDt(), DATA.getEndDt())));
            }
        });
        dialog.show();
    }


    protected static final int REQ_SELECT_IMAGE = 879;

    private void openImageSelector(boolean supportSelfie) {
        ISListConfig config = new ISListConfig.Builder()
                .multiSelect(false)// 是否多选, 默认true
                .rememberSelected(false)// 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .btnBgColor(Color.GRAY)// “确定”按钮背景色
                .btnTextColor(Color.BLUE)// “确定”按钮文字颜色
                .statusBarColor(Color.parseColor("#3F51B5"))// 使用沉浸式状态栏
                .backResId(R.drawable.ic_back)// 返回图标ResId
                //.title(getString(R.string.webview_select_picture))// 标题
                .title("选择图片")
                .titleColor(Color.WHITE)// 标题文字颜色
                .titleBgColor(Color.parseColor("#3F51B5"))// TitleBar背景色
                .needCrop(false)
                //.cropSize(16, 9, 90, 160)
                .needCamera(supportSelfie)// 第一个是否显示相机，默认true
                .maxNum(9)// 最大选择图片数量，默认9
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQ_SELECT_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 图片选择结果回调
        if (requestCode == REQ_SELECT_IMAGE
                && resultCode == Activity.RESULT_OK
                && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);
            if (CollectionUtils.isNotEmpty(pathList)) {

                // 创建根目录
                File rootDir = new File(Environment.getExternalStorageDirectory(), "SmartTodo" + File.separator + "img" + File.separator + "curriculum");
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }

                // 指定输出文件
                File cropImageFile = new File(rootDir, System.currentTimeMillis() + ".jpg");

                // 图片裁剪
                Uri u = new Uri.Builder().scheme("file").path("//" + pathList.get(0)).build();

                CropImage.activity(u)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setActivityTitle("图片裁剪")
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        .setCropMenuCropButtonTitle("Done")
                        .setOutputUri(Uri.fromFile(cropImageFile))
                        .start(this);

            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                btnSetCover.setVisibility(View.GONE);
                imgCover.setImageURI(result.getUri());
                imgCover.setVisibility(View.VISIBLE);

                if (DATA != null && !TextUtils.isEmpty(DATA.getImagePath())) {
                    File rootDir = new File(DATA.getImagePath());
                    if (rootDir.exists()) {
                        rootDir.delete();
                    }
                }
                DATA.setImagePath(result.getUri().getPath());
                if (DATA_ID != 0) {
                    ServiceFactory.getInstance().getCurriculumService().saveImgCover(DATA_ID, result.getUri().getPath());
                }

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }
}
